package com.muli.muwai.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muli.muwai.entity.IntfFinShareTrend;
import com.muli.muwai.exception.MyDefinedEnum;
import com.muli.muwai.mapper.ShareTrendMapper;
import com.muli.muwai.service.ShareTrendService;
import com.muli.muwai.util.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ShareTrendServiceImpl extends ServiceImpl<ShareTrendMapper, IntfFinShareTrend> implements ShareTrendService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sharetrend(List<String[]> sharetrend) throws Exception {
        List<IntfFinShareTrend> list = getIntfFinShareTrends(sharetrend);
        for (IntfFinShareTrend trend : list) {
            Timestamp shareTime = trend.getShareTime();
            QueryWrapper<IntfFinShareTrend> queryWrapper = new QueryWrapper();
            queryWrapper.eq("share_time",shareTime);
            IntfFinShareTrend trend1 = baseMapper.selectOne(queryWrapper);
            if(trend1!=null){
                trend.setId(trend1.getId());
            }

        }
        //有ID则增加  无ID则更新
        saveOrUpdateBatch(list);
    }

    private List<IntfFinShareTrend> getIntfFinShareTrends(List<String[]> sharetrend) throws Exception {
        int j = 0;
        List<IntfFinShareTrend> list = new ArrayList<>();
        ////定义可能出现错误列
        int line = 0;
        for (int i = 0; i < sharetrend.size(); i++) {
            String[] strings = sharetrend.get(i);
            IntfFinShareTrend entity = new IntfFinShareTrend();
            try {
                //获取错误列
                line = 1;
                SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
                Date date1 = sdf.parse(strings[0]);
                Timestamp timestamp1 = new Timestamp(date1.getTime());
                entity.setShareTime(timestamp1);
                entity.setShareUsers(strings[1]);
                entity.setShares(strings[2]);
                entity.setVisitback(strings[3]);
                //entity.setVisitbackRate(strings[4]);
                line = 5;
                if (strings[4].equals("")) {
                    entity.setVisitbackRate(0);
                } else {
                    entity.setVisitbackRate(Double.parseDouble(strings[4]));
                }
                entity.setNewVisitback(strings[5]);
                list.add(entity);
            } catch (Exception e) {
                int size = list.size() + 2;
                throw new Exception("第" + size + "行,第" + line + "列,格式错误");
            }
        }
        return list;
    }


}
